

var audioplayUtil = require("../../utils/audioplay.js")
var share = require("../../utils/share.js")

var app = getApp();
var id = ""; //获取分类id  
var dataParm = {}; //封装请求数据 
var shareTickets = ""
var titlegro = "" //栏目标题、
var hongbaointerval
Page({
  /**
   * 页面的初始数据
   */
  data: {
    authbtn: false,
    authbg: getApp().globalData.authImg,
    authbtn2: getApp().globalData.source + "red_packet/btn2.png",
    authdialog: getApp().globalData.source + "dialog/dialog.png",
    authdialog: getApp().globalData.source + "dialog/dialog.png",
    hidebanner: false,
    showhongbaoicon: false,
    showhongbao: false,
    hongbaodata: {},
    indicatorDots: false,
    vertical: false,
    autoplay: true,
    circular: true,
    interval: 5000,
    duration: 500,
    currentSwiper: 0,
    maxPage: 10, //每页显示最大行数
    startPoint: 1, //第几页
    totalPages: 1, //总共几页
    page: 1,
    imgUrls: [],
    showloading: true,
    showbottom: false,
    classfilyDataListProgram: [],
    indexNumberProgram: null, //当前播放音频下标
    classfilyDataList: [],
    indexNumber: null, //当前播放音频下标

    bottomtext: '已经到头啦',
    timer: '', //播放时间 播放时间统计
    currentPosition: 0, //选定音频的播放位置
    duration: 0, //选定音频的长度

    play: true,
    free: true,
    url: "",
    mainView: 1,
    swiperCurrent: 0,
    
    swiperList: [getApp().globalData.source + "/ttbt_image_icon/generalize/1.png", getApp().globalData.source + "/ttbt_image_icon/generalize/2.png", getApp().globalData.source + "/ttbt_image_icon/generalize/3.png", getApp().globalData.source + "/ttbt_image_icon/generalize/4.png", getApp().globalData.source + "/ttbt_image_icon/generalize/5.png"],
    indicatorDots: false,
    autoplay: true,
    rulepopshow: false,
    circular: true
    
  },
  authbtn: function () {
    var vm = this
    wx.showLoading({
      title: "正在检查网络.."
    })
    this.setData({
      authbtn: true
    })
  },
  bindGetUserInfo: function (e) {
    getApp().authInfo(e);
  },
  //轮播图的切换事件 
  swiperChange: function(e) {
    console.log(e);
    this.setData({
      swiperCurrent: e.detail.current //获取当前轮播图片的下标
    })
  },


  rulePopShow: function() {
    var that = this
    this.setData({
      rulepopshow: !that.data.rulepopshow
    })
  },
  rulePopHide: function(e) {
    var that = this
    this.setData({
      rulepopshow: !that.data.rulepopshow
    })

  },
  // swiperChange: function(e) {
  //   this.setData({
  //     currentSwiper: e.detail.current
  //   })
  // },
  tobannerdetails: function(e) {
    var vm = this
    var index = e.currentTarget.dataset.index;
    if (vm.data.imgUrls[index].isH5 == 0) {
      //跳转原生详情页
      wx.navigateTo({
        url: "../../day_day_listen/details/details?id=" + vm.data.imgUrls[index].urlAddress + "&season=" + 1,
        success: function() {},
        fail: function() {}
      })
    } else {
      //跳转h5详情页
      wx.navigateTo({
        url: "../../webview/webview?url=" + vm.data.imgUrls[index].urlAddress,
        success: function() {},
        fail: function() {}
      })
    }
  },

  jumptotal: function() {
    wx.navigateTo({
      url: '../../my/mydetail/mydetail',
    })

    this.setData({
      showhongbao: false,
      showhongbaoicon: false
    })
  },
  //检测该页面是否有红包显示
  checkhongbao: function() {
    var vm = this
    var data = {
      "pageConfig": "栏目列表页",
      "userId": wx.getStorageSync("userId")
    }
    getApp().request(getApp().globalData.https + "hd/listen/classify/random",
      "post", data,
      function(res) {
        console.log("红包数据：" + JSON.stringify(res))
        //state=1时,显示红包就开始倒计时，隐藏掉红包入口
        if (res.state == 1) {
          var time = 15
          vm.setData({
            showhongbaoicon: true
          })
          if (!vm.data.isweb) {
            hongbaointerval = setInterval(function() {
              if (time <= 0) {
                clearInterval(hongbaointerval)
                vm.setData({
                  showhongbaoicon: false
                })
              }
              time--;
            }, 1000)
            vm.setData({
              hongbaodata: res
            })
          }
        } else {
          vm.setData({
            showhongbaoicon: false
          })
        }
      },
      function(res) {});
  },

  openhongbao: function() {
    this.setData({
      showhongbao: true
    })
    //领取红包
    var vm = this
    var data = {
      "userId": wx.getStorageSync("userId"),
      "state": 1,
      "tb": vm.data.hongbaodata.tb
    }
    this.setData({
      showhongbaoicon: false
    })
    getApp().request(getApp().globalData.https + "hd/listen/classify/random/savetb",
      "post", data,
      function(res) {},
      function(res) {});
  },

  closeredpockets: function() {
    this.setData({
      showhongbao: false,
    })
  },

  bottombar: function() {

  },

  share: function() {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    var that = this;

    if (id == "-1") {
      this.getList();
    } else {
      this.getdata();
    }
    if (this.data.status === 1) {
      var that = this;
      audioplayUtil.playaudio(e, that)
    }

    var showhomeicon = options.showhomeicon == "fx" ? true : ""; //判断是分享页进入还是小程序正常进入
    if (showhomeicon) {
      this.setData({
        showhomeicon: showhomeicon
      })
    }

    // this.getbanner()
  },

  getbanner: function() {
    var that = this;
    //加载首页banner数据
    console.log(that.data.programId)
    var data = {
      "cateId": that.data.programId
    }
    getApp().requestLoading(getApp().globalData.https + "programResource/cateBannerList",
      "get", data, "加载中...",
      function(res) {
        if (res.code == 0) {
          // 获取系统信息 
          that.setData({
            imgUrls: res.data,
          });
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },


  getdata: function() {
    var that = this;
    var url
    var usersIds = wx.getStorageSync("userId") == "" ? -1 : wx.getStorageSync("userId")
    dataParm = {
      startPoint: that.data.page,
      maxPage: that.data.maxPage,
      userId: usersIds
    }
    if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
      url = "programResource/popularizeProgram" //统一节目列表
      //调用查询数据列表方法
    } else {
      url = "programResource/popularizeProgram" //统一节目列表 
    }
    that.setData({
      url: url
    })
    that.getDataList(url, dataParm);
  },

  /**
   * 播放音频
   */
  play: function(e) {
    var that = this;
    let audioList = this.data.classfilyDataListProgram
    var indexNumbers = e.currentTarget.dataset.indexnumber; //当前操作对象的 index
    // 是否启用h5 
    var id = audioList[indexNumbers].id;
    wx.setStorageSync("programid", id);
    var season = e.currentTarget.dataset.season;
    var h5Url = audioList[indexNumbers].h5Url;
    if (audioList[indexNumbers].useH5 != 1) {
      //跳转页面，使用h5
      wx.navigateTo({
        url: "../../day_day_listen/details/details?id=" + id + "&season=" + season,
        success: function() {
          //console.log("../../day_day_listen/details/details?id=" + id + "&season=" + season)
          //console.log("url===上-")
          console.log("跳转前集数" + season)
          console.log("点击了播放" + season)
          console.log('跳转到news页面成功') // success              
        },
        fail: function() {
          console.log('跳转到news页面失败') // fail 
        }
      })
    } else {
      if (wx.getStorageSync("userId") == "" || wx.getStorageSync("userId") == undefined) {
        wx.navigateTo({
          url: '../../login/login',
        })
      } else {
        audioplayUtil.stopaudio(e, that)
        var id = e.currentTarget.dataset.id
        var programid = wx.getStorageSync("programid");
        if (id == programid) {
          console.log("同一个节目")
          if (wx.getStorageSync("status") == 1) {
            setInterval(function() {
              audioplayUtil.setDuration(that)
            }, 1000)
          } else {
            audioplayUtil.playaudio(null, that)
          }
        }
        that.setData({
          currentPosition: '00:00'
        })
        console.log("播放")
        var indexNumberProgram = e.currentTarget.dataset.indexnumber;
        console.log("点击了栏目indexNumberProgram=" + indexNumberProgram)
        var indexNumber = e.currentTarget.dataset.season - 1;

        that.setData({
          indexNumberProgram: indexNumberProgram,
          indexNumber: indexNumber,
          pause: true, //暂停
          play: false, //播放
        })

        console.log("栏目id=" + id)
        console.log("播放中的栏目id=" + programid)
        //根据栏目id查询栏目
        var data = {
          startPoint: 1,
          maxPage: 10
        }
        if (id != programid) {
          that.setData({
            page: 1
          })
        }
        audioplayUtil.getProgramCurrentSeason(id, data, that)


        console.log(indexNumberProgram)
        console.log(indexNumber)
        //audioplayUtil.playaudio(e, that)
      }
    }

  },

  /**
   * 监听button暂停按钮
   */
  stop: function(e) {
    console.log(e.currentTarget.dataset.indexnumber)
    console.log("暂停")
    var that = this;
    audioplayUtil.stopaudio(e, that);
    that.setData({
      pause: false, //暂停
      play: true, //播放
      indexNumberProgram: -1
    })
  },

  /**
   * 播放进度条手动调整
   */
  bindSliderchange: function(e) {
    var that = this;
    audioplayUtil.bindSliderchange(e, that)
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    wx.hideLoading()
    this.checkhongbao();
    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease-out',
    });

    this.animation = animation;
    // console.log(this.data.status + "=========adst")
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log("监听页面卸载")
  },


  /**
   * 获取必听精选数据列表
   */
  getList: function() {
    var that = this;
    var usersIds = wx.getStorageSync("userId") == "" ? -1 : wx.getStorageSync("userId")
    dataParm = {
      startPoint: that.data.page,
      maxPage: that.data.maxPage,
      userId: usersIds
    }
    app.requestLoading(app.globalData.https + "programResource/chargeProgram/" + usersIds,
      "get", dataParm, "加载中...",
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          var dt = res.data;
          console.log(dt)
          if (res.data.data.length > 0) {
            // 获取系统信息  
            that.setData({
              classfilyDataListProgram: that.data.classfilyDataListProgram.concat(res.data.data),
              totalPages: dt.totalPages
            });
          } else {
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 3000
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 3000
          })
        }

        that.setData({
          showloading: false
        })
      }
    )
  },
  /**
   * 获取栏目数据列表
   */
  getDataList: function(url, dataParm) {
    var that = this;
    app.requestLoading(app.globalData.https + url,
      "get", dataParm, "加载中...",
      function(res) {
        wx.stopPullDownRefresh()
        if (res.code == 0) {
          var dt = res.data;
          console.log(dt)
          if (res.data.data.length > 0) {
            // 获取系统信息  
            that.setData({
              classfilyDataListProgram: that.data.classfilyDataListProgram.concat(res.data.data),
              totalPages: dt.totalPages
            });
          } else {
            if(that.data.page==1){
              that.setData({
                showbottom:true,
                bottomtext:'暂时还没有数据'
              })
            }
            wx.showToast({
              title: res.message,
              icon: 'none',
              duration: 3000
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: 'none',
            duration: 3000
          })
        }

        that.setData({
          showloading: false
        })
      }
    )
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var that = this;
    var url = that.data.url;
    this.setData({
      page: 1,
      showbottom: false,
      classfilyDataListProgram: []
    })
    if (id == "-1") {
      this.getList()
    } else {
      this.getdata();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var that = this;
    var url = that.data.url;
    if (that.data.page < that.data.totalPages) {
      that.setData({
        page: that.data.page + 1
      })
      var userids = wx.getStorageSync("userId") === "" ? -1 : wx.getStorageSync("userId");
      console.log(userids)
      dataParm = {
        userId: userids,
        categoryId: id,
        startPoint: that.data.page,
        maxPage: that.data.maxPage
      }
      console.log(dataParm)

      if (id == "-1") {
        that.getList()
      } else {
        that.getDataList(url, dataParm);
      }
    } else {
      that.setData({
        showbottom: true
      })
    }
  },


  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(e) {
    var that = this;
    var userIds = wx.getStorageSync("userId")
    if (e.from === 'button') {
      // 来自页面内转发按钮 
      var id = e.target.dataset.id
      var imageUrl = e.target.dataset.img
      var imageUrl = getApp().globalData.shareurl
      var title = e.target.dataset.title
      return {
        imageUrl: encodeURI(imageUrl),
        title: wx.getStorageSync("userInfo").nickName + '邀您一起听《' + title + "》",
        path: "/pages/day_day_listen/details/details" + "?userIds=" + userIds + "&id=" + id + "&showhomeicon=fx" + "&commission=1",
        success(res) {
          //分享成功
          console.log("进入右上角..分享")
        },
        fail(e) {},
        //分享完成
        complete() {}
      }
    } else {
      var imageUrl = getApp().globalData.shareurl
      return {
        imageUrl: encodeURI(imageUrl),
        title: wx.getStorageSync("userInfo").nickName + '邀您一起听《' + title+"》",
        path: "/pages/day_day_listen/details/details" + "?userIds=" + userIds + "&id=" + that.data.programId +"&showhomeicon=fx",
        success(res) {
          console.log("success")
          //分享成功
          console.log("进入右上角..分享")
        },
        fail(e) {
          console.log("fail")
        },
        //分享完成
        complete() {
          console.log("complete")
        }
      }
    }

    //share.onShare(that, data)
  },

  getGroupID: function(datas) { //获取分享群id
    wx.getShareInfo({
      shareTicket: shareTickets[0],
      success: function(res) {
        var encryptedData = res.encryptedData;
        var iv = res.iv;
        wx.login({
          success: function(res) {
            var code = res.code;
            console.log(code)
            var userId = datas.userId;
            var programId = datas.programId;
            var shareSource = datas.shareSource;
            var shareStatus = datas.shareStatus;
            var survivalTime = datas.survivalTime;
            var data = {
              'wxEncryptedData': encryptedData,
              "wxIv": iv,
              "userId": userId,
              "programId": programId,
              "shareSource": shareSource,
              //"shareStatus": shareStatus,
              //"survivalTime": survivalTime,
              "wxCode": code
            };
            console.log(data)
            //处理获取分享群信息
            app.request(app.globalData.https + "programResource/myProgramShare",
              "post", data,
              function(res) {
                console.log(res)
              },
              function(res) {
                console.log(res)
              }
            )
          }
        })
      }
    })
  },



  /**
   * 个人用户分享保存服务器方法调用
   */
  singleGroupId: function(data) {
    console.log("个人分享。。。。。。")
    app.request(app.globalData.https + "programResource/myProgramShare", //处理获取分享群信息
      "post", data,
      function(res) {
        if (res.code == 0) {
          console.log("调用接口" + res)
          console.log(res)
        }
      },
      function(res) {
        console.log(res)
      }
    )
  },


  /**
   * 跳转到播放详情页面
   */
  todetails: function(e) {
    let audioList = this.data.classfilyDataListProgram
    var indexNumbers = e.currentTarget.dataset.index; //当前操作对象的 index
    var season = e.currentTarget.dataset.season;
    var id = audioList[indexNumbers].id;
    // 是否启用h5 
    var h5Url = audioList[indexNumbers].h5Url;
    //wx.setStorageSync("programid", id);
    console.log("h5链接----" + h5Url);
    this.setData({
      playBthidShow: "play"
    })
    var vm = this
    vm.setData({
      play: true,
      pause: false,
      indexNumberProgram: -1
    })
    wx.navigateTo({
      url: "../day_day_listen/details/details?id=" + id + "&season=" + season,
      success: function() {
        //console.log("../../day_day_listen/details/details?id=" + id + "&season=" + season)
        //console.log("url===上-")
        console.log("跳转前集数" + season)
        console.log("点击了播放" + season)
        console.log('跳转到news页面成功') // success              
      },
      fail: function() {
        console.log('跳转到news页面失败') // fail 
      }
    })
  },

  search: function() {
    wx.navigateTo({
      url: "../../search/search",
      success: function() {
        console.log('跳转到news页面成功') // success              
      },
      fail: function() {
        console.log('跳转到news页面失败') // fail 
      }
    })
  },

  /**
   * 获取免费节目列表
   */
  free: function() {
    //调用查询数据列表方法
    dataParm = {
      categoryId: id,
      startPoint: startPoint,
      maxPage: that.data.maxPage
    }
    var url = "programResource/program/" + id //统一节目列表
    var that = this;
    this.setData({
      free: true,
      pay: false,
      url: url
    })

    that.getDataList(url, dataParm);
  },

  /**
   * 获取收费的节目列表
   */
  pay: function() {
    wx.navigateTo({
      url: '../spread/spread',
    })
  },
  // 回到首页
  gohome: function() {
    wx.switchTab({
      url: '/pages/style/style',
    })
  },
})